import { Provide } from '@midwayjs/core';
import { ethers } from "ethers";

declare global {  //设置全局属性
  interface Window {  //window对象属性
    ethereum: any;   //加入对象
  }
}

@Provide()
export class WalletService {

  signer:any = null;
  provider:any = null;
  ethereum:any = null;
  async getWallet(addr:string) {
    if (this.ethereum == null) {
    
        // If MetaMask is not installed, we use the default provider,
        // which is backed by a variety of third-party services (such
        // as INFURA). They do not have private keys installed,
        // so they only have read-only access
        console.log("MetaMask not installed; using read-only defaults")
        this.provider = ethers.getDefaultProvider()
    
    } else {
    
        // Connect to the MetaMask EIP-1193 object. This is a standard
        // protocol that allows Ethers access to make all read-only
        // requests through MetaMask.
        this.provider = new ethers.BrowserProvider(this.ethereum)
    
        // It also provides an opportunity to request access to write
        // operations, which will be performed by the private key
        // that MetaMask manages for the user.
        this.signer = await this.provider.getSigner();

    }


    let num =await this.provider.getBlockNumber()

    let balance = await this.provider.getBalance(addr)
    // 
    console.log(num)
    console.log(balance)
    console.log(ethers.formatEther(balance))
    return {
      num,
      balance:ethers.formatEther(balance)
    };
  }
}
